<template>
  <view class="sign-in-page">
    <!-- 签到按钮 -->
    <view class="sign-in-container">
      <!-- 查看我的积分 -->

      <view class="my-integral" @click="gotoMyIntegral()">
        <text>我的</text>
        <text>积分</text>
      </view>

      <view class="sign-in-button" :class="{ signed: isSigned, noSignIn: !isSigned }" @click="handleSignIn">
        <text>{{ isSigned ? '已签' : '签到' }}</text>
        <text class="sign-number" v-if="signedScore !== 0">+{{ signedScore }}</text>
      </view>
      <text class="sign-tip">每连续签到7天可获得更多积分</text>
    </view>

    <!-- 日历 -->
    <view class="calendar">
      <view class="calendar-header">每日记录（{{ currentMonth }}月）</view>
      <view class="week-row">
        <view class="week-day" v-for="(day, index) in weekDays" :key="day.date">
          {{ day }}
        </view>
      </view>
      <view class="calendar-grid">
        <!-- 补齐空白（前导空格） -->
        <view v-for="n in startDay" :key="'empty' + n" class="calendar-day empty"></view>
        <!-- 渲染日期 -->
        <view
          v-for="(day, index) in days"
          :key="day.date"
          class="calendar-day"
          :class="{
            signed: signInInclued(day.date),
            today: day.isToday && !signInInclued(day.date)
          }"
        >
          {{ day.date }}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isSigned: false,
      signedScore: 0,
      signedDay: 0,
      currentMonth: new Date().getMonth() + 1, // 获取当前月份
      todayDate: new Date().getDate(), // 获取当天日期
      weekDays: ['日', '一', '二', '三', '四', '五', '六'], // 星期标题
      days: [], // 存放当月所有日期
      signedDates: [], // 已签到的日期
      startDay: 0, // 当月 1 号是星期几
      userId: 0
    }
  },
  onLoad() {
    this.userId = getApp().globalData.userInfo.id
    this.getData()

    const signed = uni.getStorageSync('signed')
    if (signed === '') {
      this.isSigned = false
      this.signedDay = 0
      this.signedScore = 0
    } else {
      // 反序列化
      const obj = JSON.parse(signed)
      // 获取当前日期
      const day = new Date().getDate()
      // console.log(obj, day, obj.signedDay !== day)
      // 如果存储的信息不是当前签到信息，重置
      if (obj.signedDay !== day) {
        // console.log('是主力')
        this.isSigned = false
        this.signedDay = 0
        this.signedScore = 0
      } else {
        this.isSigned = true
        this.signedDay = obj.signedDay
        this.signedScore = obj.signedScore
      }
    }
  },
  methods: {
    async getData() {
      const { data: res } = await uni.request({
        url: this.$domain.data + '/getSignInList/' + this.userId
      })

      // console.log(res)
      if (res.status !== 200) {
        this.$checkStatus(res.status)
        return
      }

      this.signedDates = res.data
    },

    signInInclued(date) {
      // console.log(date)
      for (let i = 0; i < this.signedDates.length; i++) {
        const element = this.signedDates[i]
        const time = new Date(element.create_time)
        // console.log(date, time.getDate())
        if (date === time.getDate()) {
          return true
        }
      }
      return false
    },

    async handleSignIn() {
      if (!this.isSigned) {
        const { data: res } = await uni.request({
          url: this.$domain.data + '/signInData/' + this.userId,
          header: getApp().globalData.header,
          method: 'POST'
        })

        // console.log(res)
        if (res.status !== 200) {
          if (res.status === 222) {
            this.$checkStatus(res.status, res.message)
            return
          }

          this.$checkStatus(res.status)
          return
        }
        uni.showToast({
          icon: 'success',
          title: '签到成功'
        })
        this.getData()
        // console.log(res)
        this.signedScore = res.data.score
        this.signedDay = res.data.signDay
        // 存入缓存
        uni.setStorageSync('signed', JSON.stringify({ signedDay: this.signedDay, signedScore: this.signedScore }))
        this.isSigned = true
      }
    },
    generateCalendar() {
      let year = new Date().getFullYear()
      let month = this.currentMonth
      let daysInMonth = new Date(year, month, 0).getDate() // 计算本月天数
      let firstDay = new Date(year, month - 1, 1).getDay() // 获取本月 1 号是星期几

      this.startDay = firstDay // 存储首日星期几
      this.days = Array.from({ length: daysInMonth }, (_, i) => ({
        date: i + 1,
        isToday: i + 1 === this.todayDate
      }))
    },
    gotoMyIntegral() {
      uni.navigateTo({
        url: '/pages/integral/myIntegral'
      })
    }
  },
  mounted() {
    this.generateCalendar()
  }
}
</script>

<style lang="scss" scoped>
/* 页面整体 */
.sign-in-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f8f8f8;
  min-height: 100vh;
  box-sizing: border-box;
  padding: 40upx;
}

/* 签到按钮样式 */
.sign-in-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  padding: 60upx;
  border-radius: 20upx;
  box-shadow: 0 10upx 20upx rgba(0, 0, 0, 0.1);
  width: 90%;
  text-align: center;
  position: relative;

  .my-integral {
    top: 20upx;
    box-shadow: 0 10upx 20upx rgba(0, 0, 0, 0.1);
    right: 20upx;
    width: 70upx;
    height: 70upx;
    border-radius: 50%;
    position: absolute;
    background-color: #ffa726;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    font-size: 20upx;
  }
}

@keyframes floatAndPulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

.sign-in-button {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 160upx;
  height: 160upx;
  background-color: #ffa726;
  color: white;
  font-weight: bold;
  border-radius: 50%;
  text-align: center;
  box-shadow: 0 4px 10px rgba(255, 167, 38, 0.5);
  cursor: pointer;

  .sign-number {
    margin-top: 5upx;
    font-size: 30upx;
  }
}

.noSignIn {
  animation: floatAndPulse 1.5s infinite ease-in-out;
}

.signed {
  background: #ffa726 !important;
  animation: signTransition 0.5s ease-in-out forwards;
}

@keyframes signTransition {
  0% {
    transform: scale(1);
    background-color: #ffa726;
  }
  50% {
    transform: scale(0.8);
    background-color: #ffcc80;
  }
  100% {
    transform: scale(1);
    background-color: #ff9800;
  }
}

/* 提示 */
.sign-tip {
  margin-top: 20upx;
  font-size: 24upx;
  color: #888;
}

/* 日历 */
.calendar {
  width: 90%;
  background: white;
  margin-top: 40upx;
  padding: 40upx;
  border-radius: 20upx;
  box-shadow: 0 10upx 20upx rgba(0, 0, 0, 0.05);
}

.calendar-header {
  font-size: 32upx;
  font-weight: bold;
  margin-bottom: 20upx;
  text-align: center;
}

/* 星期标题 */
.week-row {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  column-gap: 10upx;
  font-weight: bold;
  color: #666;
  // background-color: #ff8c00;

  .week-day {
    width: 80upx;

    text-align: center;
  }
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  gap: 10upx;
}

/* 每一天的样式 */
.calendar-day {
  width: 80upx;
  height: 80upx;
  // width: 100%;
  // height: 100%;
  // background-color: aquamarine;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32upx;
  color: #333;
}

/* 已签到的日期（圆形框） */
.signed {
  background: #ff8c00;
  border-radius: 50%;
  color: white;
}

/* 今日日期（高亮） */
.today {
  color: #ff8c00; /* 深海军蓝 */
  font-weight: bold;
}

/* 用于补齐日历的前面空白 */
.empty {
  visibility: hidden;
}
</style>
